<template>
    <el-container>
        <el-main class="wrapper">
            <v-breadcrumb v-bind:breadcumb="breadcumb"></v-breadcrumb>
            <section class="panel" :style="{'min-height': mainHeight+'px'}">
                <div class="panel-body">
                    <div class="btn-group" style="margin-bottom: 15px">
                        <el-button @click="create" type="primary" icon="fa fa-plus"
                                   size="small"> 新增
                        </el-button>
                        <el-button @click="list" type="primary" icon="fa fa-refresh"
                                   size="small"> 刷新
                        </el-button>
                    </div>
                    <el-table v-loading="loading"
                              element-loading-text="努力加载中..."
                              element-loading-spinner="el-icon-loading"
                              :data="tableData" :border="true" style="width: 100%">
                        <el-table-column prop="id" label="编号" width="80px"></el-table-column>
                        <el-table-column prop="title" label="名称" width="250px"></el-table-column>
                        <el-table-column prop="img" label="背景图" width="200px">
                            <template slot-scope="scope">
                                <el-popover
                                        placement="top"
                                        trigger="click">
                                    <img :src="scope.row.img" />
                                    <el-button slot="reference" style="border: none;height: 55px;padding: 0">
                                        <img :src="scope.row.img" style="height: 55px;width: 150px"/>
                                    </el-button>
                                </el-popover>
                            </template>
                        </el-table-column>
                        <el-table-column prop="created_at" label="时间" width="150px">
                            <template slot-scope="scope">{{ scope.row.created_at ? moment(scope.row.created_at).format('YYYY-MM-DD HH:mm') : ''}}</template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button icon="fa fa-trash" @click="destory(scope.row.id)" type="danger" size="mini" plain> 删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="pagination">
                        <div class="pagination-total">共 <em>{{pageData.total}}</em> 张背景</div>
                        <el-pagination  v-if="!loading && pageData && pageData.last_page > 1" background layout="prev, pager, next, jumper"
                                        :page-size="pageData.per_page"
                                        :total="pageData.total" :current-page="pageData.current_page"
                                        @current-change="handleCurrentChange">
                        </el-pagination>
                    </div>
                </div>
            </section>
        </el-main>

        <el-dialog
            :title="dialogTitle"
            custom-class="bh-dialog"
            top="23vh"
            @open="resetForm('formData')"
            :visible.sync="updateDialog"
            width="500px">
            <el-form :model="formData" :rules="rules" ref="formData" label-width="80px" class="demo-ruleForm">
                <el-form-item required label="标题：" prop="title">
                    <el-input v-model="formData.title" placeholder="请填写图片标题"></el-input>
                </el-form-item>
                <el-form-item required label="背景图：" prop="img">
                    <el-upload
                        class="avatar-uploader"
                        :action="upload"
                        :show-file-list="false"
                        :headers="myHeaders"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload" name="pic">
                        <img v-if="formData.img" :src="formData.img" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="updateDialog = false">取 消</el-button>
                <el-button type="primary" @click="update('formData')">确 定</el-button>
              </span>
        </el-dialog>
    </el-container>
</template>
<script>
    import {mapGetters} from 'vuex';
    import vBreadcrumb from '../layout/breadcrumb.vue';
    import {BackList,BackUpdate,BackDestory} from '../../utils/axios';

    export default {
        components: {vBreadcrumb},
        data() {
            return {
                breadcumb: [{name: "背景管理"},],
                tableData: [],//列表数据
                pageData: [],//分页数据
                updateDialog: false,
                search: {page:null},//筛选
                dialogTitle: '',
                //用户表单
                formData: {
                    id: 0,
                    title: '',
                    img: '',
                },
                rules: {
                    title: [{required: true, message: '请填写图片标题', trigger: 'blur'}],
                    img: [{required: true, message: '请上传图片地址', trigger: 'change'}],
                },
            }
        },
        activated() {
            this.$store.dispatch('setActive', '/back');
            this.list();
        },
        computed: {
            ...mapGetters(['active', 'mainHeight', 'loading', 'upload']),
            myHeaders() {
                var token = this.$storage.get('token');
                return {
                    'Authorization': 'Bearer ' + token,
                    'Accept': 'application/json'
                }
            },
        },
        methods: {
            //回调1
            handleAvatarSuccess(res, file) {
                if (res.code) {
                    this.$message.error(res.msg);
                } else {
                    this.formData.img = res.data;
                }
            },
            //回调2
            beforeAvatarUpload(file) {
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isLt2M;
            },
            //分页
            handleCurrentChange(val) {
                this.search.page = val;
                this.list();
            },
            //获取背景图片列表
            list() {
                this.$store.dispatch('setLoading', true);
                BackList({params: this.search}).then((response) => {
                    if (response.code) {
                        this.$message.error(response.msg);
                    } else {

                        this.$store.dispatch('setLoading', false);
                        this.tableData = response.data.data;
                        this.pageData = response.data;
                    }
                    console.info(response)
                })
            },
            //编辑
            create() {
                this.formData = {
                    id: 0,
                    title: '',
                    img: '',
                },
                this.updateDialog = true;
                this.dialogTitle = '新增背景图';
            },
            //编辑
            edit(info) {
                this.formData = {
                    id: info.id,
                    title: info.title,
                    img: info.img,
                }
                this.updateDialog = true;
                this.dialogTitle = '编辑背景图';
            },
            //更新
            update(formName) {
                let that = this;
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        BackUpdate(this.formData).then((e) => {
                            if (e.code) {
                                this.$message.error(e.msg);
                            } else {
                                this.$message({
                                    type: 'success',
                                    duration: '1000',
                                    message: e.msg,
                                    onClose: () => {
                                        this.updateDialog = false;
                                        this.list();
                                    }
                                });
                            }
                        });
                    }
                });
            },
            //删除
            destory(id) {
                this.$confirm('确定要删除该背景图吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    BackDestory({params: {id: id}}).then((response) => {
                        if (response.code) {
                            this.$message.error(response.msg);
                        } else {
                            this.list();
                        }

                    });
                }).catch(() => {
                });
            },
            //重置表单
            resetForm(formName) {
                if (this.$refs[formName] !== undefined) {
                    this.$refs[formName].resetFields();
                }
            },
        },
    }
</script>
<style>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        /*position: relative;*/
        /*left: 50%;*/
        /*margin-left: -89px;*/
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
